package com.kotodama.interfaces.web.controllers;

import com.kotodama.application.cqrs.bus.CommandBus;
import com.kotodama.application.cqrs.bus.QueryBus;
import com.kotodama.application.cqrs.commands.tenant.CreateTenantCommand;
import com.kotodama.application.cqrs.queries.tenant.GetTenantByIdQuery;
import com.kotodama.domain.entities.Tenant;
import com.kotodama.domain.enums.TenantStatus;
import com.kotodama.infrastructure.tenant.context.TenantContext;
import com.kotodama.interfaces.web.dto.CreateTenantRequest;
import com.kotodama.interfaces.web.dto.TenantResponse;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/api/tenants")
public class TenantController {

    private final CommandBus commandBus;
    private final QueryBus queryBus;

    public TenantController(CommandBus commandBus, QueryBus queryBus) {
        this.commandBus = commandBus;
        this.queryBus = queryBus;
    }

    @PostMapping
    @PreAuthorize("hasRole('ADMIN')")
    public ResponseEntity<TenantResponse> createTenant(@RequestBody CreateTenantRequest request) {
        // 使用CQRS命令创建租户
        CreateTenantCommand command = new CreateTenantCommand(
                TenantContext.getTenantId(),
                request.getName(),
                TenantStatus.valueOf(request.getStatus() != null ? request.getStatus() : "ACTIVE"));

        Tenant savedTenant = commandBus.execute(command);

        TenantResponse response = new TenantResponse();
        response.setId(savedTenant.getId());
        response.setName(savedTenant.getName().getValue());
        response.setStatus(savedTenant.getStatus().toString());

        return ResponseEntity.ok(response);
    }

    @GetMapping("/{id}")
    public ResponseEntity<TenantResponse> getTenantById(@PathVariable String id) {
        // 使用CQRS查询获取租户
        GetTenantByIdQuery query = new GetTenantByIdQuery(TenantContext.getTenantId(), id);
        Tenant tenant = queryBus.execute(query);

        TenantResponse response = new TenantResponse();
        response.setId(tenant.getId());
        response.setName(tenant.getName().getValue());
        response.setStatus(tenant.getStatus().toString());

        return ResponseEntity.ok(response);
    }

    @GetMapping("/current")
    public ResponseEntity<String> getCurrentTenant() {
        return ResponseEntity.ok("当前租户ID: " + TenantContext.getTenantId());
    }
}
